import { useCssVar, useEventListener, useTitle } from '@vueuse/core';
import axios from 'axios';
import localforage from 'localforage';
import { getConfig } from './api/modules/system/config/utils';
import { staticHost } from './api/utils/image';
import { connectWs, pageStatus, sendMsg, websocket } from './global/config/websocket';
import { popoverNotice } from './global/window/notify';
import usePageStore from './store/page';
import type { IconStyle } from './store/page/types';
import useSystemStore from './store/system';
import { isDev } from './utils/common/bin';
import { joinUrl } from './utils/file/format';
import { sysConfig } from './views/modules/tool/system-setting/data/data';
import type { SysConfig } from './views/modules/tool/system-setting/data/types';
import { openWindow } from './global/window/window';
import Help from './views/widget/help/Help.vue';

interface DynamicComponents {
  component: any;
  path: string;
}
/* 系统组件, */
export const systemComponents = ref<DynamicComponents[]>([]);

/*
  系统默认图标分类
  将资源目录所有图标文件名统一一致，则可以一键切换风格
*/
export const DEFAULT_ICON = ref<IconStyle>('system');
export const globalConfig = ref<SysConfig>();
const modules = import.meta.glob('./views/modules/**/*.vue');

/**
 * @description: 加载系统图片
 */
export const loadSystemImages = async () => {
  const systemStore = useSystemStore();
  const pageStore = usePageStore();
  /* 读取系统图标风格 */
  DEFAULT_ICON.value = pageStore.$state.theme.iconStyle;
  const host = systemStore.$state.developer.resourceHost || staticHost.value;
  const staticUrl = joinUrl(host.replace('/images', ''), 'data.json');
  try {
    const result = await localforage.getItem('images');
    if (!result) {
      const response = await fetch(staticUrl);
      const data = await response.json();
      await localforage.setItem('images', data);
    }
  } catch (error) {
    // error
  }
};

/**
 * @description:
 * 加载系统组件
 * 自定义组件，请勿以AX开头
 * 不会加载任何以开头的VUE文件
 */
export const loadSystemComponents = () => {
  for (const path in modules) {
    const result = path.match(/.*\/(.+).vue$/);
    if (result) {
      const component: any = modules[path];
      /* 包含AX的文件，不会被加载，过滤生成的文件 */
      if (!path.includes('AX')) {
        systemComponents.value.push({
          component: markRaw(defineAsyncComponent(component)),
          path,
        });
      }
    }
  }
};

/**
 * @description: AXIOS配置
 */
export const setAxios = () => {
  const store = useSystemStore();
  axios.defaults.baseURL = store.$state.developer.baseURL;
  axios.defaults.timeout = store.$state.developer.timeout * 1000;
};

/**
 * @description: 禁止鼠标滚动缩放页面
 */
export const setEvent = () => {
  const wheelEvent = (e: WheelEvent) => {
    if (e.ctrlKey) {
    }
  };
  useEventListener('wheel', wheelEvent, {
    passive: false,
  });
};

/**
 * @description:
 * 设置主题变量
 * 需要迁移到服务器
 */
export const setCssVar = () => {
  const store = usePageStore();
  const { fontSize, theme: themeColor } = store.$state.theme;
  const fontSizeCss = useCssVar('--font-size', document.body);
  const cssAttrs = ['--primary', '--underpainting'];
  cssAttrs.forEach(v => {
    useCssVar(v, document.body).value = (store.$state.theme as any)[v.replace('--', '')];
  });
  const primary = useCssVar('--primary', document.body);
  fontSizeCss.value = `${fontSize}px`;
  primary.value = `${themeColor}`;
};

/**
 * @description: 屏幕检测
 */
export const screenDetection = () => {
  if (devicePixelRatio > 1) {
    popoverNotice(`你的设备/页面启用了缩放`);
  }
};

/**
 * @description: 初始化websocket
 */
export const initialWebsocket = () => {
  connectWs();
  if (!websocket.value) return;
  websocket.value.onopen = () => {
    sendMsg('Hello');
  };
  websocket.value.onmessage = (data: MessageEvent) => {
    const noticeData: SocketOnline = JSON.parse(data.data);
    popoverNotice(`${noticeData.username || '匿名用户'}上线了`);
  };
  websocket.value.onclose = () => {
    pageStatus.value = 'maintenance';
  };
  websocket.value.onerror = e => {
    // 发生错误后切换成维护页面
    pageStatus.value = 'maintenance';
  };
};

/**
 * @description:
 * 获取系统设定参数
 * 版本&静态资源
 */
export const getSettings = async () => {
  const data = await getConfig(sysConfig.value);
  const store = useSystemStore();
  if (data) {
    const document = useTitle();
    if (!data) {
      return;
    }
    globalConfig.value = data;
    document.value = data.pageConfig.pageTitle;
    let resourceHost = data.pageConfig.staticResourceUrl;
    /* 读取静态资源地址 */
    if (resourceHost) {
      staticHost.value = resourceHost;
      store.$state.developer.resourceHost;
    }
    /* 检测版本 */
    if (store.$state.version !== data.pageConfig.version) {
      popoverNotice(`系统已经更新至${data.pageConfig.version},请刷新页面`);
    }
    store.$state.version = data.pageConfig.version;
  }
};
